<template>
  <eui-background type="common">
    <eui-navbar ref="EuiNavBar" title="价签核验" :storeName="sUserStoreName" :storeId="sUserStore" @onClickStore="clickStore"/>
    <view class="top-view">
      <eui-search-bar ref="RdsSearchBar" v-model="searchText" placeholder="请输入商品条码、编码、PLU码或关键字"
                      leftIcon="icon-saoyisao"
                      @confirm="searchConfirm" @leftIconClick="scanCode" radius="30" :showFilterIcon="false"/>
    </view>
    <view class="list-view">
      <eui-tab :tabs="tabData" :value="currTab" :show-badge="true" @change="tabChange"/>
    </view>
    <view class="table-view">
      <scroll-view :scroll-y="true" :style="{height: scrollHeight + 'rpx'}">
        <eui-table :column="columns" :listData="tabListData" :loading="false">
          <template v-for="(item) in columns" #[item.slot]="Props">
            <view v-if="item.slot === 'errMsg' && currTab === 0" class="td-err-msg" style="text-align:center;">
              <eui-icons style="display: block;" size="16rpx" color="red" type="info" @click="showErrMsg($event, Props.item['c_err_msg'])"/>
            </view>
            <view v-if="item.slot === 'errMsg' && currTab === 1" class="td-err-msg" style="text-align:center;">
              <eui-icons style="display: block;" size="16rpx" color="green" type="info" @click="showErrMsg($event, '核验成功')"/>
            </view>
          </template>
        </eui-table>
      </scroll-view>
    </view>
    <view class="bottom-view">
      <eui-button title="清空" type="base2" @click="clearData" :disabled="allListData.length === 0" />
      <eui-button title="生成打印申请单" type="base" @click="createLabelReq" :disabled="currTab !== 0 || tabListData.length === 0" />
    </view>
  </eui-background>
</template>

<script setup lang="ts">
import {ref} from 'vue';
import {onLoad, onShow} from "@dcloudio/uni-app";
import {useSystemInfoStore} from "@/store/useSystemInfo";
import Enjoy from "@/common/enjoy";
import {useMainStore} from "@/store/modules/store";
import service from '../../../common/service';
import {getRdsUrl, rdsRequest,} from '@/hooks/rdsServices';
import {validateStores} from "@/hooks/useValidateMethod";
import dayjs from 'dayjs';

const sUserStore = ref(''); // 用户默认机构编码
const sUserStoreName = ref(''); // 用户默认机构名称
const sUserStoreType = ref('');
const sUser = ref(''); // 当前用户编码
const searchText = ref('');
const scrollHeight = ref(0);
const tabData = ref([
    {name: '核验失败', corner: 0},
    {name: '核验成功', corner: 0},
]);
const columns = ref([
  {title: '商品编码', isFixed: true, align: 'left', key: 'c_gcode', width: 1, fixedW: 0.02},
  {title: '商品条码', isFixed: true, align: 'left', key: 'c_barcode', width: 1, fixedW: 0.02},
  {title: '核验结果', isFixed: false, align: 'center', key: 'c_err_msg', slot: 'errMsg', width: 1, fixedW: 0.02},
]);
// 首先，假设需要导入一些必要的依赖或者类型定义，比如日期相关的类型等，此处仅示意，按实际项目需求调整
// import { 可能需要导入的类型等 } from '对应模块路径';

interface Tb_log_label_print {
  // 对应原类中的自增列，主键（非聚集）
  c_id: number;
  // 租户
  c_tenant_id: string;
  // 机构
  c_store_id: string;
  // 部门
  c_adno: string;
  // 商品编码，与示例格式中的字段对应类型保持一致格式
  c_gcode: string;
  // 商品名称
  c_name: string;
  // 条码，与示例格式中的字段对应类型保持一致格式
  c_barcode: string;
  // 规格
  c_model: string;
  // 基本单位
  c_basic_unit: string;
  // 产地
  c_produce: string;
  // 零售价
  c_price: number | null;
  // 会员价
  c_price_mem: number | null;
  // 促销价
  c_pro_price: number | null;
  // 促销会员价
  c_pro_price_mem: number | null;
  // 促销起止日期
  c_pro_dt: string;
  // 会员促销起止日期
  c_mem_pro_dt: string;
  // 打印日期，假设使用Date类型来表示日期时间（可按实际项目对日期类型的处理来调整）
  c_print_dt: Date;
  // 打印人
  c_print_userno: string;
  // 打印数量
  c_print_qtty: number;
  // 识别码，默认识别码字段：商品编码、商品名称、商品条码、规格、基本单位、产地、零售价、会员价、促销价、促销会员价、促销起止日期、会员促销起止日期
  c_identity_code: string;
  // 价签样式Id
  c_labelstyle_id: string;
  // 价签类型
  c_labelstyle_type: number;

  // 扩展字段部分，以下是示例中已有的扩展字段，同样添加到接口定义里

  // 部门名称（假设后续会有相关赋值等逻辑，目前只是示例占位）
  c_adname: string;
  // 部门外文名称（同理，属于扩展属性）
  c_adname_en: string;
  // 价签核验错误信息
  c_err_msg: string;
  // 序号
  c_sort: number;
}
const allListData = ref([] as Tb_log_label_print[]);
const tabListData = ref([] as Tb_log_label_print[]);
const currTab = ref(0);
const systemInfoStore = useSystemInfoStore(); // 系统参数
const mainStore = useMainStore();
const rdsUrl = getRdsUrl();

onLoad(() => {
  const {loginInfo} = mainStore;
  if (!['2', '3'].includes(loginInfo.sUserStoreHier)) {
    clickStore();
  }
});

onShow(() => {
  setTimeout(() => {
    let info = uni.createSelectorQuery().select(".table-view");
    info.boundingClientRect((data) => {
      //获取列表高度
      let windowHeight = systemInfoStore?.systemInfo?.windowHeight || 600;
      let windowWidth = systemInfoStore?.systemInfo?.windowWidth || 750;
      let height = windowHeight - data?.top - 80;
      //转换rpx
      scrollHeight.value = height / (windowWidth / 750);
    }).exec()
  }, 1000)
});

const clickStore = () => {
  let parms = Enjoy.GetDialogParms();
  parms.CallBack = SelectionChanged;
  parms.SelectionType = '机构选择';
  parms.SelectedItems = sUserStore.value;
  parms.WhereList = [{'c_col': 'c_type', 'c_oper': '包含', 'c_value': '2,3', 'c_logic': '而且'}];
  Enjoy.OpenDialog(parms);
};

const SelectionChanged = async (event) => {
  if (event.SelectionType == '机构选择') {
    const storeId = event.BackParms.Key;
    const storeName = event.BackParms.Value;
    const result = await validateStores(
        { fieldName: 'c_store_id', newValue: storeId },
        { ischecklimit: true, firstValueMode: true }
    );
    if (!['2', '3'].includes(result.c_type)) {
      uni.showToast({
        title: '当前机构不是分店或配送中心!',
        icon: 'none',
        duration: 3000,
      });
      return;
    }
    const {loginInfo} = mainStore;
    // 更新机构信息
    sUserStoreName.value = storeName;
    sUserStore.value = storeId;
    sUser.value = loginInfo.sUser;
    sUserStoreType.value = result.c_type;
    // 回填全局登录机构
    loginInfo.sUserStore = storeId;
    loginInfo.sUserStoreName = storeName;
  }
};

const scanCode = () => {
  uni.scanCode({
    success: function (res) {
      if (res.result != undefined && res.result != '') {
        searchConfirm({value: res.result})
      }
    },
  });
};

const searchConfirm = async (e) => {
  if (!['2', '3'].includes(sUserStoreType.value)) {
    await uni.showToast({
      title: '当前机构不是分店或配送中心！',
      icon: 'none',
      duration: 1000,
    });
    clickStore();
    return;
  }
  const code = e.value;
  if (!code) {
    return;
  }
  if (allListData.value.some(item => item.c_barcode === code || item.c_gcode === code)) {
    uni.showToast({
      title: '该商品已存在！',
      icon: 'none',
      duration: 3000,
    });
    return;
  }
  searchText.value = code;
  service.enjoyShowLoading('核验中...');
  const param = {
    queryCode: 'repair',
    storeId: sUserStore.value,
    gcode: code,
    invOver: '0',
    changeDa: dayjs().format('YYYY-MM-DD'),
    billType: '',
    billId: '',
    changeReason: '',
    extention: '',
  };
  const objData : Tb_log_label_print[] = await rdsRequest(rdsUrl.apiApi, '管易通价签打印', 'CheckPrintLabel', param, '');
  service.enjoyHideLoading();
  if (objData) {
    const sort = allListData.value.length;
    objData.forEach((item, index) => {
      item.c_sort = sort + index;
      allListData.value.push(item);
      if (item.c_err_msg && currTab.value === 0) {
        tabListData.value.push(item);
      }
      if (!item.c_err_msg && currTab.value === 1) {
        tabListData.value.push(item);
      }
      let corner0 = allListData.value.filter(item => !!item.c_err_msg).length;
      let corner1 = allListData.value.filter(item => !item.c_err_msg).length;
      tabData.value[0].corner = corner0;
      tabData.value[1].corner = corner1;
    });
  }
};

const createLabelReq = async () => {
  uni.showModal({
    title: '提示',
    content: '是否将核验失败的商品重新生成打印申请单？',
    showCancel: true,
    success: (res) => {
      if (res.confirm) {
        doCreateLabelReq();
      }
    }
  });
}

const doCreateLabelReq = async () => {
  service.enjoyShowLoading('生成中...');
  const getBillIdReq = {
    BillIdKeyValue: {
      key: "c_id",
      value: ""
    },
    BillVariable: "",
    TableName: "rds_bc_gds_label_apply",
    BillName: "商品价签打印申请单"
  }
  const billId = await rdsRequest(rdsUrl.mainApi, '单号生成服务', 'EnjoyGetBillId', getBillIdReq,'BN1');
  service.enjoyHideLoading();

  service.enjoyShowLoading('生成中...');
  const errList = allListData.value.filter(data => !!data.c_err_msg).map(data => {
    return {
      c_id: "",
      c_tenant_id: "",
      c_sort: data.c_sort,
      c_gcode: data.c_gcode,
      c_barcode: data.c_barcode,
      c_apply_n: data.c_apply_n,
      c_unit: data.c_unit,
      c_model: data.c_model,
      c_price: data.c_price,
      c_adno: data.c_adno,
    }
  });
  const param = {
    NewList: [
      {
        c_tenant_id: "",
        c_id: "",
        c_bill_type: "BN1",
        c_status: "0",
        c_store_id: sUserStore.value,
        c_adno: "",
        c_mk_dt: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        c_mk_userno: sUser.value,
        c_approve_status: "1",
        c_au_userno: "",
        c_print_userno: "",
        c_print_n: 0,
        c_note: "",
        c_modify_userno: sUser.value,
        c_modify_dt: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      }
    ],
    ModifiedList: [],
    DelList: [],
    TableName: "tb_mo_gds_label_apply",
    PrimaryKeys: ["c_tenant_id", "c_id"],
    BillSet: {
      BillIdKeyValue: {
        key: "c_id",
        value: billId
      },
      BillVariable: "",
      BillName: "商品价签打印申请单",
      TableName: "tb_mo_gds_label_apply",
    },
    ChildData: [
      {
        ChildTableName: "tb_mo_gds_label_apply_g",
        ParentTableName: "tb_mo_gds_label_apply",
        ChildColumnNames: ["c_id"],
        ParentColumnNames: ["c_id"],
        ChildSaveModel: {
          NewList: errList,
          ModifiedList: [],
          DelList: [],
          TableName: "tb_mo_gds_label_apply_g",
          PrimaryKeys: ["c_tenant_id", "c_id", "c_sort"],
        }
      }
    ]
  }
  await rdsRequest(rdsUrl.bcApi, '商品价签打印申请单', 'EnjoyBillSaveNew', param, 'BN1');
  service.enjoyHideLoading();
  uni.showToast({
    title: `生成成功，单号：${billId}`,
    icon: 'none',
    duration: 3000,
  });
  clearData();
}

const clearData = () => {
  allListData.value = [];
  tabListData.value = [];
  tabData.value.forEach(item => item.corner = 0);
  uni.showToast({
    title: '清除成功！',
    icon: 'none',
    duration: 3000,
  });
}

const showErrMsg = (event, c_err_msg) => {
  // 这里的click会触发2次，第一次的event是null，需要处理一下，否则弹窗会出现2次
  if (!event) {
    return;
  }
  event.preventDefault();
  uni.showModal({
    title: '核验结果',
    content: c_err_msg,
    showCancel: false,
  });
}

const tabChange = async (i) => {
  currTab.value = i;
  tabListData.value = allListData.value.filter(data => i === 0 ? !!data.c_err_msg : !data.c_err_msg);
  tabData.value[i].corner = tabListData.value.length;
}

</script>


<style scoped lang="scss">

.table-view {
  width: 100%;
}

.bottom-view {
  position: absolute;
  bottom: 40rpx;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 80rpx;
  box-sizing: border-box;
  padding: 5rpx;
}
</style>
